#ifndef CHATCLIENT_H
#define CHATCLIENT_H

#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include "model.h"

class ChatClient : public QObject
{
    Q_OBJECT

public:
    explicit ChatClient(QObject* parent = nullptr);
    ~ChatClient();

    void connectToServer(const QString& host, quint16 port);
    void disconnectFromServer();
    void login(const QString& username, const QString& password = "");
    void sendMessage(const model::Message& message);
    bool isConnected() const;

signals:
    void connected();
    void disconnected();
    void loginSuccess(const model::UserInfo& userInfo);
    void loginFailed(const QString& reason);
    void messageReceived(const model::Message& message);
    void errorOccurred(const QString& error);

private slots:
    void onConnected();
    void onDisconnected();
    void onReadyRead();
    void onErrorOccurred(QAbstractSocket::SocketError error);

private:
    void processData(const QByteArray& data);
    void processLoginResponse(const QJsonObject& json);
    void processChatMessage(const QJsonObject& json);

    QTcpSocket* m_socket;
    QString m_currentUser;
    bool m_isLoggedIn;
};

#endif // CHATCLIENT_H

